#include "widget.h"
#include "ui_widget.h"

#include <QByteArray>
#include <QFile>
#include <QTcpServer>
#include <QTcpSocket>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
    ,server(new QTcpServer(this))
{
    ui->setupUi(this);

    this->setWindowTitle("热更新demo服务器");
    this->setFixedSize(300,400);

    if (this->server->listen(QHostAddress::LocalHost, 1234))
    {
        this->ui->textEdit->append("服务器开始运行!");
    }
    else
    {
        this->ui->textEdit->append("服务器运行失败");
    }

    connect(this->server, &QTcpServer::newConnection,[=]{
        static int count=0;
        QTcpSocket *clientSocket = this->server->nextPendingConnection();

        this->ui->textEdit->append(QString("有一台客户机连接到服务器"));

        connect(clientSocket, &QTcpSocket::readyRead, [this, clientSocket]() {
            this->ui->textEdit->append("接收到信息");
            QByteArray msg = clientSocket->readAll();
            this->ui->textEdit->append(msg);

            if (msg == "hot_refresh_demo_plugin.dll") {

                send_file(clientSocket,QString(":/hot_refresh_demo_plugin.dll"));

            } else if (msg == "hot_refresh_demo_plugin_2.dll") {

                send_file(clientSocket,QString(":/hot_refresh_demo_plugin_2.dll"));

            }
        });
        connect(clientSocket,&QTcpSocket::disconnected,[=]{
            clientSocket->deleteLater();
        });
    });
}

void Widget::send_file(QTcpSocket *clientSocket,QFile file){
    if (!file.open(QIODevice::ReadOnly)) {
        qDebug() << "Failed to open file for reading";
        clientSocket->close();
        return ;
    }

    const int bufferSize = 4096; // 每次发送 4KB
    QByteArray buffer;

    while (!(buffer = file.read(bufferSize)).isEmpty()) {
        clientSocket->write(buffer);
        clientSocket->flush(); // 确保数据立即发送
    }

    // 发送结束标志
    clientSocket->write("END_OF_FILE");
    clientSocket->flush();

    file.close();
}

Widget::~Widget()
{
    delete ui;
}

